package com.gp.service.impl;

import com.gp.dao.MenuDao;
import com.gp.entity.Menu;
import com.gp.service.MenuService;
import com.gp.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 来一杯凉咖
 * @create 2022/3/8 18:41
 */
@Service
public class MenuServiceImpl implements MenuService{
    @Autowired
    private MenuDao menuDao;

    /**
     * @param menus 所有的菜单
     * @param pid  父id
     * @return
     */
    private List<Menu> findChildren(List<Menu> menus,Integer pid){//pid=24
        //子菜单
        List<Menu> children=new ArrayList<Menu>();
        //遍历所有菜单
        for(Menu m:menus){
            //得到指定pid得得子菜单
            if(m.getParentId().equals(pid)){
                children.add(m);
            }
        }
        //遍历pid下的所有子菜单-- 方法得递归调用
        for(Menu c:children){
            c.setChildren(findChildren(menus,c.getMenuId()));
        }
        return children;
    }

    @Override
    public CommonResult findMenu() {
        //获取登录者得信息
//        Role role = (Role) session.getAttribute("employee");
//        Integer roleId = role.geteRole();
//        //根据角色查询该角色具有的菜单
// TODO: 2022/3/8
        List<Menu> menuList = menuDao.findMenuByRoleId(1);
        //为菜单分层
        //1. 查询所有的一级菜单。
        List<Menu> firstMenus=new ArrayList<Menu>();
        for(Menu menu:menuList){
            if(menu.getParentId()==0){
                firstMenus.add(menu);
            }
        }
        //2.找到一级菜单下所有子菜单
        for(Menu first:firstMenus){
            //找到一级菜单下的所有子菜单
            List<Menu> children = findChildren(menuList, first.getMenuId());
            first.setChildren(children);
        }
        //最多二级菜单 方法得递归调用。
        System.out.println(firstMenus);
        return new CommonResult(200,"查询菜单成功",firstMenus);
    }
}
